﻿using System;
using HDM.NexusEngine.Core;

namespace HDM.NexusEngine.Shooter
{
    public class PlayerCharacter : Entity
    {
        private const double SPEED = 512; // pixels per second.
        private bool _dead;
        private readonly BulletManager _bulletManager;
        private readonly Texture _bulleTexture;
        private readonly Vector _gunOffset = new Vector(55, 0, 0);
        private const double FIRE_RECOVERY = 0.25;
        private double _fireRecoveryTime = FIRE_RECOVERY;

        public bool IsDead { get { return _dead; } }

        public PlayerCharacter(TextureManager textureManager, BulletManager bulletManager)
        {
            _bulletManager = bulletManager;
            _bulleTexture = textureManager.Get("bullet");
            _sprite.Texture = textureManager.Get("player_ship");
            // spaceship is quite big, scale it down.
            _sprite.SetScale(0.5, 0.5);
        }

        public void Update(double elapsedTime)
        {
            _fireRecoveryTime = Math.Max(0, (_fireRecoveryTime - elapsedTime));
        }

        public void Render(Renderer renderer)
        {
            renderer.DrawSprite(_sprite);
            //Render_Debug();
        }

        public void Move(Vector amount)
        {
            amount *= SPEED;
            _sprite.SetPosition(_sprite.GetPosition() + amount);
        }

        public void Fire()
        {
            if (_fireRecoveryTime > 0) return;

            _fireRecoveryTime = FIRE_RECOVERY;
            var bullet = new Bullet(_bulleTexture);
            bullet.SetColor(new Color(0, 1, 0, 1));
            bullet.SetPosition(_sprite.GetPosition() + _gunOffset);
            _bulletManager.Shoot(bullet);
        }

        public Vector GetPosition()
        {
            return _sprite.GetPosition();
        }

        internal void OnCollision(Enemy enemy)
        {
            _dead = true;
        }

        internal void OnCollision(Bullet bullet)
        {
            _dead = true;
        }
    }
}